/**
 * 402. 移掉 K 位数字
 * https://leetcode-cn.com/problems/remove-k-digits/
 */

/**
 * @param {string} num
 * @param {number} k
 * @return {string}
 */
function removeKdigits(num, k) {
  const stack = new Array(num.length).fill('0');
  let restCountToRemove = k;
  let top = -1;
  for (let i = 0; i < num.length; i += 1) {
    while (restCountToRemove && top >= 0 && num[i] < stack[top]) {
      top -= 1;
      restCountToRemove -= 1;
    }
    top += 1;
    stack[top] = num[i];
  }
  let firstValidIndex = 0;
  while (stack[firstValidIndex] === '0') {
    firstValidIndex += 1;
  }
  const restLength = num.length - k;
  if (firstValidIndex >= restLength) {
    return '0';
  }
  return stack.slice(firstValidIndex, num.length - k).join('');
}

console.log(removeKdigits('1432219', 3) === '1219');
console.log(removeKdigits('10200', 1) === '200');
console.log(removeKdigits('10', 2) === '0');
console.log(removeKdigits('5337', 2) === '33');
